// 登录的逻辑
//1.获取元素
const usernameInp = document.querySelector('.username>input');
const passwordInp = document.querySelector('.password>input');
const form = document.querySelector('form');
const span = document.querySelector('form>span')


form.addEventListener('submit', async e => {
    e = e || window.event;
    //阻断默认事件传播
    try{e.preventDefault()} catch(err) {e.returnValue = false};
    const username = usernameInp.value;
    const password = passwordInp.value;
    //非空验证
    if(!username || !password) return window.alert('请完整填写登录信息');
    //发送请求
    const res = await pAjax({
        url: 'http://localhost:8888/users/login',
        method: 'POST',
        data:`username=${username}&password=${password}`,
        dataType: 'json'
    })
    //根据返回的数据，进行下列操作
    if(res.code === 0) {span.style.visibility = 'visible'; return;};
    //代码能来到这里，说明登录成功了
    window.localStorage.setItem('id', res.user.id);
    window.localStorage.setItem('token', res.token);
    const url = window.localStorage.getItem('url');
    window.localStorage.removeItem('url');
    window.location.href = `./${url ? url : 'index'}.html`
    
})
